#pragma once
#include <iostream>
#include <vector>
#include "Log.hpp"
#include "InetAddr.hpp"
#include "Mutex.hpp"

using namespace std;
using namespace LogModule;
using namespace MutexModule;

class Route
{
private:
    bool IsExit(InetAddr &peer)
    {
        for (auto &e : _online_user)
        {
            if (e == peer)
            {
                return true;
            }
        }
        return false;
    }

    void User_Add(InetAddr &peer)
    {
        LOG(LogLevel::INFO) << "添加一个聊天用户";
        _online_user.push_back(peer);
    }

    void User_Delete(InetAddr &peer)
    {
        //LOG(LogLevel::DEBUG) << "删除一个用户";
        for (auto iter = _online_user.begin(); iter < _online_user.end(); iter++)
        {
            if (*iter == peer)
            {
                LOG(LogLevel::INFO) << "成功删除用户:" << peer.StringAddr();
                _online_user.erase(iter);
                break;
            }
        }
    }

public:
    Route()
    {
    }

    void MessageRoute(int _sockfd, const string &messages, InetAddr &addr)
    {
        LockGuard lockguard(_lock);

        if (!IsExit(addr))
        {
            User_Add(addr);
        }
        string result_messeage = "[" + addr.StringAddr() + "]" + messages;
        LOG(LogLevel::INFO)<<result_messeage;
        for (auto &e : _online_user)
        {
            sendto(_sockfd, result_messeage.c_str(), result_messeage.size(), 0, (const struct sockaddr *)&e.Addr(), sizeof(e.Addr()));
        }
        if (messages == "QUIT")
        {
            LOG(LogLevel::INFO) << "删除一个用户" << addr.StringAddr();
            User_Delete(addr);
        }
    }

    ~Route()
    {
    }

private:
    vector<InetAddr> _online_user;
    Mutex _lock;
};